package com.zx.template.config;


import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.zx.template.constant.BaseConstants;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * MP 统一对创建时间，更新时间，做更新
 */
@Component
public class CreateUpdateTimeFillHandle implements MetaObjectHandler {

    /**
     * 新增数据执行
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        boolean hasSetter = metaObject.hasSetter(BaseConstants.CREATE_TIME);
        if (hasSetter) {
            this.setFieldValByName(BaseConstants.CREATE_TIME, new Date(), metaObject);
            this.setFieldValByName(BaseConstants.UPDATE_TIME, new Date(), metaObject);
        }
    }

    /**
     * 更新数据执行
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        Object val = getFieldValByName(BaseConstants.UPDATE_TIME, metaObject);
        if (val == null) {
            this.setFieldValByName(BaseConstants.UPDATE_TIME, new Date(), metaObject);
        }
    }

}
